package com.atguigu.spzx.common.handler.interceptor;

import com.atguigu.spzx.model.entity.h5.UserInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * title:
 * author: zgl
 * date: 2024/1/17
 * description：
 */
@Component
public class SpzxAuthInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;

    public static final ThreadLocal<UserInfo> threadLocal= new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get("spzx:user:login" + token);
        threadLocal.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
